
import React, { useState, useEffect } from 'react';//引入react
import PubSub from 'pubsub-js'

import { renderAppById } from '../util'
window.PubSub = PubSub
function FriendStatus(props) {
    const isOnline = useFriendStatus(props.friend.id);
    console.log('isOnline', isOnline)
    if (isOnline === null) {
        return 'Loading...';
    }
    return isOnline ? 'Online' : 'Offline';
}

function FriendListItem(props) {
    const isOnline = useFriendStatus(props.friend.id);
    console.log('isOnline', isOnline)

    return (
        <li style={{ color: isOnline ? 'green' : 'black' }}>
            {props.friend.name}-{isOnline ? '在线' : '离线'}
        </li>
    );
}

function useFriendStatus(friendID) {
    const [isOnline, setIsOnline] = useState(null);
    useEffect(() => {
        function handleStatusChange(status, data) {
            // console.log('data', data)
            setIsOnline(data.isOnline);
        }
        PubSub.subscribe(friendID, handleStatusChange);
        return () => {
            // ChatAPI.unsubscribe(friendID, handleStatusChange);
        };
    });

    return isOnline;
}


export default function App() {
    return <div>
        <FriendStatus friend={{ id: 'AAA', name: '小明' }} />
        <FriendListItem friend={{ id: 'AAA', name: '小明' }} />
    </div>
}
// 测试代码
setTimeout(() => {
    PubSub.publish('AAA',{isOnline:false})
}, 3000);


